package com.qf.utils;

import com.qf.core.ParseRequestData;
import com.qf.pojo.Student;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ParseRequestDataUtils {

    public static <T> ParseRequestData parseRequest(HttpServletRequest request,Class<T> clazz,String path){

        ParseRequestData<T> parseRequestData = new ParseRequestData<>();

        //创建文件上传工厂类的对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传类的对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        HashMap<String, String> map = new HashMap<>();
        try {
            //解析请求
            List<FileItem> list = upload.parseRequest(request);
            for (FileItem fileItem : list) {
                if(fileItem.isFormField()){//文本数据

                    String name = fileItem.getFieldName();
                    String value = fileItem.getString("UTF-8");

                    String v = map.get(name);
                    if(v == null){//说明是第一次添加
                        map.put(name,value);
                    }else{//不是第一次添加就需要拼接（多选框的情况）
                        map.put(name,v + "," + value);
                    }

                }else{//二进制数据

                    //D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload\\student
                    //D:\\apache-tomcat-8.0.49\\webapps\\Day23_upload_war_exploded\\upload\\teacher
                    String realPath = request.getServletContext().getRealPath(path);


                    //文件存储目录 -- 自定义路径\\用户名
                    realPath = realPath + File.separator + map.get("username");
                    File file = new File(realPath);
                    if(!file.exists()){
                        file.mkdirs();
                    }

                    String fileName = fileItem.getName();//获取文件名

                    //自定义路径\\用户名\\tx01.jpg
                    realPath = realPath + File.separator + fileName;//拼接路径

                    InputStream in = fileItem.getInputStream();
                    if(in.available() != 0){
                        FileOutputStream out = new FileOutputStream(realPath);
                        parseRequestData.setIn(in);
                        parseRequestData.setOut(out);
                        map.put("photo",path + File.separator + map.get("username") + File.separator + fileName);
                    }
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry);
        }

        T t = null;
        try {
            t = clazz.newInstance();
            //将map中的数据映射到实体类对象中
            BeanUtils.populate(t,map);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
        System.out.println(t.getClass());
        parseRequestData.setT(t);

        return parseRequestData;
    }
}
